<script>
import { getNetworkOk } from "@/utils/utils.js";
import { getMessage_count } from "@/static/js/message.js";
import homeApi from "@/static/js/enterpriseServer/index.js";
import { goEasy } from "@/utils/goEasy.js";
import Vue from "vue";
import { mapState } from "vuex";
export default {
  onLaunch: function () {
    // #ifdef APP-PLUS

    // 监听网络状态变化
    this.networkMonitor();

    // #endif

    if (uni.getStorageSync("token")) {
      this.filtration();
      this.getUserInfo();
    }
  },
  onShow: function () {
    if (uni.getStorageSync("token")) {
      setTimeout(() => {
        goEasy();
        this.getMessageCount();
      }, 1500);
      // #ifdef APP-PLUS
      // #endif
    }
  },
  onHide: function () {
    //断开goeasy连接
    //	#ifdef APP-PLUS
    // this.$goeasy.disconnect({
    //   onSuccess: function () {
    //     console.log("GoEasy disconnect successfully.");
    //   },
    //   onFailed: function (error) {
    //     console.log(
    //       "Failed to disconnect GoEasy, code:" +
    //         error.code +
    //         ",error:" +
    //         error.content
    //     );
    //   },
    // });
    // #endif
  },
  methods: {
    //获取用户信息
    getUserInfo() {
      homeApi.getUserInfo().then((res) => {
        let that = this;
        if (res.code === 1) {
          this.$store.state.userInfo = res.data;

          this.$store
            .dispatch("createZIM")
            .then((zim_x) => {
              that.getZIM(res.data, that);
            })
            .catch((err) => {
              console.log("createZIM", err);
            });
        }
      });
    },

    //初始化ZIM.企服聊天
    getZIM(userInfo, that) {
      // 注册监听“运行时错误信息”的回调
      that.$store.state.zim.on("error", function (zim, errorInfo) {
        console.log("error", errorInfo.code, errorInfo.message);
      });

      // 更新会话列表
      that.$store.state.zim.on(
        "conversationChanged",
        function (zim, { infoList }) {
          // console.log("更新会话列表conversationChanged", infoList);
          that.$store.commit("updata_ConversationList", infoList);
        }
      );

      // 注册监听“网络连接状态变更”的回调
      that.$store.state.zim.on(
        "connectionStateChanged",
        function (zim, { state, event, extendedData }) {
          // 当长时间网络连接断开导致SDK内部登出时，需要重新登录
          if (state == 0 && event == 3) {
            console.log("网络连接状态变更");
            that.$store.dispatch("ZIMLogin");
          }
        }
      );

      // 注册监听“令牌即将过期”的回调
      that.$store.state.zim.on("tokenWillExpire", function (zim, { second }) {
        // 可以在这里调用 renewToken 接口来更新 token
        // 新 token 生成可以参考上文
        let token = uni.getStorageSync("zegoToken");
        uni.removeStorageSync("zegoToken");
        zim
          .renewToken(token)
          .then(function ({ token }) {
            // 更新成功
            uni.setStorageSync("zegoToken", token);
            that.$store.dispatch("ZIMLogin");
          })
          .catch(function (err) {
            // 更新失败
            that.$store.dispatch("ZIMLogin");
          });
      });

      that.$store.dispatch("ZIMLogin");
    },

    //请求企服过滤数据数据
    filtration() {
      homeApi.filtration().then((res) => {
        let arr = res.data;
        let userIds = arr.map((item) => item.user_id);
        //存到vuex中
        this.$store.commit("set_filtration", userIds);
      });
    },

    //打开软件监听网络状态
    networkMonitor() {
      let tryNet = 0; // 记录尝试的次数
      const MAX_TRY_NET = 20; // 最大尝试次数
      let wasNoNetwork = false; // 标记上一次是否为无网络状态

      // 检测网络是否正常
      let timer = setInterval(async () => {
        let netOk = await getNetworkOk();

        if (netOk) {
          if (wasNoNetwork) {
            // 当前网络恢复正常，并且上一次是无网络状态
            wasNoNetwork = false;
            plus.runtime.restart();
          }
          clearInterval(timer); // 在这里直接退出循环，避免无限刷新
          return;
        } else {
          wasNoNetwork = true;
        }

        tryNet++;
        if (tryNet > MAX_TRY_NET) {
          clearInterval(timer);
          uni.showModal({
            title: "提示",
            content: "系统检测到您的网络存在问题，请点击确定打开网络设置",
            success: function (res) {
              if (res.confirm) {
                console.log("用户点击确定");
                var UIApplication = plus.ios.import("UIApplication");
                var NSURL = plus.ios.import("NSURL");
                var setting = NSURL.URLWithString("app-settings:");
                var application = UIApplication.sharedApplication();
                // 打开应用的设置页面
                application.openURL(setting);
              } else if (res.cancel) {
                console.log("用户点击取消");
                const exitIosAPP = uni.requireNativePlugin("CGF-ExitIosApp");
                exitIosAPP.exitIosApp();
              }
            },
          });
        }
      }, 500);
    },

    //请求未读消息数
    async getMessageCount() {
      let res = await getMessage_count({});
      if (res.code == 1) {
        let message = res.data;
        let num =
          Number(message.comment) +
          Number(message.message) +
          Number(message.like) +
          Number(message.wendahuifu) +
          Number(message.dengnilaida);
        console.log("set_wdNum", num);
        this.$store.commit("set_wdNum", num);
      }
    },
  },
  computed: {
    ...mapState(["wdNum", "serverNum"]), // 将 vuex 的状态映射为计算属性
  },
  watch: {
    wdNum(newVal, oldVal) {
      let serverNum = Vue.prototype.$store.state.serverNum
        ? Vue.prototype.$store.state.serverNum
        : 0;
      if (serverNum + newVal > 0) {
        uni.setTabBarBadge({
          index: 3,
          text: newVal + serverNum > 99 ? "99+" : "" + (newVal + serverNum),
        });
      }
    },
    deep: true, // 如果 `wdNum` 是对象或数组需要深度监听
  },
};
</script>

<style lang="scss">
@import "uview-ui/index.scss";

/*每个页面公共css */
@import "./static/css/public.css";

@import "colorui/main.css";
@import "colorui/icon.css";

body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    "Microsoft Yahei", sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

// page{
//   background: #fff !important;
// }

view {
  word-break: break-all;
  word-wrap: break-word;
}

view,
image,
text {
  box-sizing: border-box;
  flex-shrink: 0;
}

::-webkit-scrollbar {
  display: none;
}

.main {
  width: 100vw;
  height: 100%;
  line-height: 1;
  box-sizing: border-box;
  position: relative;
}

/deep/ .uni-scroll-view-refresh__spinner > circle {
  color: #2979ff !important;
}

/deep/ .uni-scroll-view-refresh-inner > svg {
  fill: #2979ff !important;
}
</style>
